package com.hyh.baowenlioaworking.controller;

import com.hyh.baowenlioaworking.commom.Constants;
import com.hyh.baowenlioaworking.commom.R;
import com.hyh.baowenlioaworking.model.dtos.loginParam;
import com.hyh.baowenlioaworking.model.Admin;
import com.hyh.baowenlioaworking.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @BelongsPackage: com.hyh.baowenlioaworking.controller
 * @ClassName AdminController
 * @Author: hyhWTX
 * @CreateTime: 2023-07-21  14:07
 * @Description: TODO (一句话描述以下该类的功能)
 * @Version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminService adminService;

    /**
     * 登录方法
     * @param loginParam
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody loginParam loginParam,HttpSession session) {
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        if (username == null || password == null) {
            return R.error(Constants.CODE_500,"Login failed");
        }
        try {
            // 解密密码
            String decryptedPassword = encryptPassword(password);
            boolean loggedIn = adminService.login(username, decryptedPassword);
            HttpSession session1 = session;
            session1.setAttribute(username,decryptedPassword);
            log.info("session1:  {}"+session1);
            System.out.println(loggedIn);
            if (loggedIn) {
                // 登录成功逻辑处理
                return R.success(Constants.CODE_200,"Login successful");
            } else {
                // 登录失败逻辑处理
                return R.error(Constants.CODE_500,"Login failed");
            }
        } catch (RuntimeException e) {
            // 异常处理
            e.printStackTrace();
            return R.error(Constants.CODE_500,"Login failed");
        }
    }
    // 加密密码
    private String encryptPassword(String password) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(password.getBytes(StandardCharsets.UTF_8));
            return DatatypeConverter.printHexBinary(digest).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to encrypt password", e);
        }
    }
    @PostMapping("/add")
    public R<String> addAdmin(@RequestBody Admin admin) {
        adminService.addAdmin(admin);
        return R.success(Constants.CODE_200, "添加成功");
    }

    /**
     * 用户退出
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("admin");
        return R.success(Constants.CODE_200,"退出成功");
    }

    @GetMapping("/getAdminByUserName/{username}")
    public List<Admin> getAdminByUserName(@PathVariable String username){
        return adminService.getAdminByUserName(username);
    }
}
